package com.cofey.config.server;

import com.cofey.config.entity.Config;
import com.cofey.config.entity.ConfigProperties;
import com.cofey.config.service.ConfigRepositoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.cloud.config.server.environment.EnvironmentRepository;
import org.springframework.util.StringUtils;

public class DatabasesEnvironmentRepository implements EnvironmentRepository {

    @Autowired
    private ConfigRepositoryService configRepositoryService;

    @Override
    public Environment findOne(String application, String profile, String label) {
        if (StringUtils.isEmpty(application) || StringUtils.isEmpty(profile))
            return null;
        Config config = configRepositoryService.findConfig(application, profile, label);
        if (config != null) {
            Environment environment = new Environment(application, StringUtils.commaDelimitedListToStringArray(profile), label, config.getVersion());
            for (ConfigProperties configProperties : config.getConfigPropertiesList()) {
                environment.add(new PropertySource(configProperties.getPropertiesName(), configProperties.getContent()));
            }
            return environment;
        }
        return new Environment(application, profile);
    }
}